<template>
  <div class="app-container">
    <!-- 页面标题和操作按钮 -->
    <div class="filter-container">
      <el-button 
        class="filter-item" 
        style="margin-left: 10px;" 
        type="primary" 
        icon="el-icon-plus" 
        @click="handleCreate"
      >
        添加活动
      </el-button>
      
    </div>

    <!-- 活动列表表格 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      />
      <el-table-column
        label="活动标题"
        prop="title"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="图标"
        prop="icon"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <img 
            v-if="scope.row.icon" 
            :src="scope.row.icon" 
            alt="活动图标" 
            class="table-icon-image"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="路由"
        prop="route"
        align="center"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="状态"
        prop="status"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
            {{ scope.row.status === '1' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="created_at"
        align="center"
        width="180"
        sortable
      />
      <el-table-column
        label="更新时间"
        prop="updated_at"
        align="center"
        width="180"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        width="320"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="info" size="mini" @click="handlePreview(row)">
            预览
          </el-button>
          <el-button type="success" size="mini" @click="handleExportRowJson(row)">
            导出JSON
          </el-button>
          <el-button 
            v-if="row.status === '1'" 
            size="mini" 
            type="warning" 
            @click="handleModifyStatus(row, '0')"
          >
            禁用
          </el-button>
          <el-button 
            v-else 
            size="mini" 
            type="success" 
            @click="handleModifyStatus(row, '1')"
          >
            启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加活动' : '编辑活动'"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 100%;"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="temp.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <ImgCutter v-on:cutDown="handleIconCutDown" :cutWidth="764" :cutHeight="266" :boxHeight="300">
            <template #open>
              <el-button type="primary" size="small">选择图标</el-button>
            </template>
          </ImgCutter>
          <el-image 
            v-if="temp.icon"
            style="width: 200px; height: 70px; margin-top: 10px; border: 1px solid #dcdfe6; border-radius: 4px;"
            :src="temp.icon"
            fit="cover">
          </el-image>
        </el-form-item>
        <el-form-item label="路由" prop="route">
          <el-input v-model="temp.route" placeholder="请输入路由" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="页面内容" prop="text">
          <el-input
            v-model="temp.text"
            type="textarea"
            :rows="3"
            placeholder="请输入活动页面json"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      title="活动预览"
      :visible.sync="previewDialogVisible"
      width="600px"
    style="padding:0px"
      :before-close="handlePreviewClose"
      class="phone-preview-dialog"
    >
      <div class="phone-preview-container">
        <div class="phone-frame">
          <div class="phone-header">
            <div class="phone-notch"></div>
          </div>
          <div class="phone-screen">
            <iframe
              ref="previewIframe"
              :src="previewUrl"
              width="100%"
              height="100%"
              frameborder="0"
              scrolling="auto"
            />
          </div>
          <div class="phone-footer">
            <div class="phone-home-button"></div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import ImgCutter from 'vue-img-cutter'
import axios from 'axios'
import { activityList,activitySave,activityDetlete } from '../../../libs/api'
export default {
  name: 'ActivityList',
  components: { Pagination, ImgCutter },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10
      },
      temp: {
        id: undefined,
        title: '',
        icon: '',
        text: '',
        route: '',
        status: '1'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      previewDialogVisible: false,
      previewUrl: '',
      rules: {
        title: [{ required: true, message: '活动标题不能为空', trigger: 'blur' }],
        route: [{ required: true, message: '路由不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取活动列表数据
    async getList() {
      this.listLoading = true
      
      try {
        const response = await activityList(this.listQuery)
        if (response.code === 1) {
          this.list = response.data.data
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '获取活动列表失败')
        }
      } catch (error) {
        console.error('获取活动列表失败:', error)
        this.$message.error('获取活动列表失败')
      } finally {
        this.listLoading = false
      }
    },
    
    // 重置表单数据
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        icon: '',
        text: '',
        route: '',
        status: '1'
      }
    },
    
    // 添加活动
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    // 编辑活动
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    // 创建数据
    async createData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            const response = await activitySave(this.temp)
            if (response.code === 1) {
              this.$message.success('创建成功')
              this.dialogFormVisible = false
              this.getList()
            } else {
              this.$message.error(response.msg || '创建失败')
            }
          } catch (error) {
            console.error('创建活动失败:', error)
            this.$message.error('创建失败')
          }
        }
      })
    },
    
    // 更新数据
    async updateData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            const response = await activitySave(this.temp)
            if (response.code === 1) {
              this.$message.success('更新成功')
              this.dialogFormVisible = false
              this.getList()
            } else {
              this.$message.error(response.msg || '更新失败')
            }
          } catch (error) {
            console.error('更新活动失败:', error)
            this.$message.error('更新失败')
          }
        }
      })
    },
    
    // 修改状态
    async handleModifyStatus(row, status) {
      const statusText = status === '1' ? '启用' : '禁用'
      this.$confirm(`确定要${statusText}这个活动吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const updateData = {
            id: row.id,
          }
          const response = await activityDetlete(updateData)
          if (response.code === 1) {
            this.getList()
          } else {
            this.$message.error(response.msg || `${statusText}失败`)
          }
        } catch (error) {
          console.error(`修改活动状态失败:`, error)
          this.$message.error(`${statusText}失败`)
        }
      })
    },
    
    // 删除活动
    handleDelete(row) {
      this.$confirm('确定要删除这个活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里应该调用API删除活动
        console.log('删除活动:', row.id)
        const index = this.list.findIndex(item => item.id === row.id)
        if (index > -1) {
          this.list.splice(index, 1)
          this.total--
        }
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      })
    },
    
    // 预览活动
    handlePreview(row) {
      this.previewUrl = `https://vrgnnycqrqts.xzxty310.com/#/?orgId=${row.id}`
      this.previewDialogVisible = true
    },
    
    // 关闭预览对话框
    handlePreviewClose(done) {
      this.previewUrl = ''
      done()
    },
    
    // 导出页面JSON
    handleExportJson() {
      if (!this.list || this.list.length === 0) {
        this.$message.warning('没有数据可导出')
        return
      }
      
      try {
        const exportData = this.list.map(item => {
          // 解析text字段为JSON
          let templateJson = ''
          try {
            if (item.text) {
              templateJson = JSON.parse(item.text)
            }
          } catch (e) {
            console.warn('解析text字段失败:', e)
            templateJson = item.text || ''
          }
          
          return {
            id: item.id,
            name: item.title,
            templateJson: JSON.stringify(templateJson),
            component: templateJson.component || '[]'
          }
        })
        
        // 创建下载链接
        const dataStr = JSON.stringify(exportData, null, 2)
        const dataBlob = new Blob([dataStr], { type: 'application/json' })
        const url = URL.createObjectURL(dataBlob)
        
        // 创建下载链接并触发下载
        const link = document.createElement('a')
        link.href = url
        link.download = `活动页面数据_${new Date().getTime()}.json`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    
    // 导出单行JSON
    handleExportRowJson(row) {
      try {
        // 解析text字段为JSON
        let templateJson = ''
        try {
          if (row.text) {
            templateJson = JSON.parse(row.text)
          }
        } catch (e) {
          console.warn('解析text字段失败:', e)
          templateJson = row.text || ''
        }
        
        const exportData = {
          id: row.id,
          name: row.title,
          templateJson: JSON.stringify(templateJson),
          component: templateJson.component || '[]'
        }
        
        // 创建下载链接
        const dataStr = JSON.stringify(exportData, null, 2)
        const dataBlob = new Blob([dataStr], { type: 'application/json' })
        const url = URL.createObjectURL(dataBlob)
        
        // 创建下载链接并触发下载
        const link = document.createElement('a')
        link.href = url
        link.download = `${row.title || '活动'}.json`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    
    // 图标裁剪成功回调
    async handleIconCutDown(v) {
      const formData = new FormData();
      // 添加文件到表单数据
      formData.append('image', v.file);

      try {
        const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        // 上传成功后更新表单中的图标地址
        this.temp.icon = response.data.data.url;
        this.$message.success('图标上传成功');
      } catch (error) {
        console.error('图标上传失败', error);
        this.$message.error('图标上传失败，请重试');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}

.filter-container .filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.image-preview {
  position: relative;
  display: inline-block;
}

.image-count {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 6px;
  border-radius: 0 4px 0 4px;
  font-size: 12px;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.preview-container {
  width: 100%;
  height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

/* 手机预览样式 */
.phone-preview-dialog .el-dialog {
  margin-top: 2vh !important;
  max-height: 95vh;
  overflow-y: auto;
}

.phone-preview-dialog .el-dialog__body {
  padding: 0 !important;
}

.phone-preview-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 10px;
  background: #f5f5f5;
  min-height: 850px;
}

.phone-frame {
  width: 375px;
  height: 812px;
  background: #000;
  border-radius: 30px;
  padding: 8px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
  position: relative;
}

.phone-header {
  height: 30px;
  background: #000;
  border-radius: 22px 22px 0 0;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-notch {
  width: 120px;
  height: 20px;
  background: #000;
  border-radius: 0 0 10px 10px;
  position: absolute;
  top: 0;
}

.phone-screen {
  width: 100%;
  height: 752px;
  background: #fff;
  border-radius: 0;
  overflow: hidden;
  position: relative;
}

.phone-screen iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

.phone-footer {
  height: 30px;
  background: #000;
  border-radius: 0 0 22px 22px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-home-button {
  width: 40px;
  height: 40px;
  border: 2px solid #333;
  border-radius: 50%;
  background: transparent;
}

/* 图标上传相关样式 */
.icon-upload-container {
  display: flex;
  align-items: center;
}

.icon-preview {
  display: flex;
  align-items: center;
  gap: 10px;
}

.icon-image {
  width: 100px;
  height: 35px;
  object-fit: cover;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.edit-btn {
  padding: 0;
  font-size: 12px;
}

.table-icon-image {
  width: 60px;
  height: 21px;
  object-fit: cover;
  border-radius: 4px;
}
</style>
